package com.anyext.storage.dialect;

public class Oracle11gDialect implements Dialect {

	@Override
	public String getLimitSql(String sql, int offset, int limit) {
		sql = sql.trim();
		String lowerSql = sql.toLowerCase();

		boolean isForUpdate = false;
		boolean isForUpdateNoWait = false;

		if (lowerSql.endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		} else if (lowerSql.endsWith(" for update nowait")) {
			sql = sql.substring(0, sql.length() - 18);
			isForUpdateNoWait = true;
		}

		StringBuffer sb = new StringBuffer(sql.length() + 128);

		if (offset <= 1) {
			sb.append("select * from ( ");
		} else {
			sb.append("select * from ( select row_.*, rownum rownum_ from ( ");
		}

		sb.append(sql);

		if (offset <= 1) {
			sb.append(" ) where rownum <= ").append(limit);
		} else {
			sb.append(" ) row_ where rownum < ").append(limit + offset).append(") where rownum_ >= ").append(offset);
		}

		if (isForUpdate) {
			sb.append(" for update");
		} else if (isForUpdateNoWait) {
			sb.append(" for update nowait");
		}

		return sb.toString();
	}

}
